﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace LiteFramework.Security
{
    /// <summary>
    /// 所有加密算法的顶层基类
    /// </summary>
    public abstract class SecurityAbs
    {
        protected const string __defaultKEY = "hykon.cn";
        protected const string __defaultIV = "~2@,5*eL";


        #region CreateIV

        /// <summary>
        /// 生成IV。加密的强随机数
        /// </summary>
        /// <returns></returns>
        public static string CreateIV()
        {
            return CreateIV(0x10);
        }

        /// <summary>
        /// 生成IV。加密的强随机数
        /// </summary>
        /// <returns></returns>
        public static string CreateIV(int len)
        {
            byte[] data = new byte[len];
            new RNGCryptoServiceProvider().GetBytes(data);
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < len; i++)
            {
                double num = ((double)data[i]) / 256.0;
                data[i] = (byte)((num * 76.0) + 47.0);
                builder.Append(Convert.ToString(data[i], len).ToUpper());
            }

            return builder.ToString();
        }

        #endregion


        /// <summary>
        /// string转换为byte数组
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        protected static byte[] getBytes(string s)
        {
            return getBytes(s, null);
        }
        /// <summary>
        /// string转换为byte数组
        /// </summary>
        /// <param name="s"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        protected static byte[] getBytes(string s, Encoding encoding)
        {
            if (encoding == null) encoding = Encoding.Default;

            if (s == null)
            {
                s = string.Empty;
            }
            s = s.PadRight(8, '@');//.Substring(0, 8);

            char[] chars = s.ToCharArray();// new char[] { s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7] };
            return encoding.GetBytes(chars);
        }

        /// <summary>
        /// 字符串转byte数组
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        protected static byte[] Base64StringToBytes(string s)
        {
            if (s == null)
            {
                s = string.Empty;
            }

            return Convert.FromBase64String(s);
        }

        protected static string BytesToBase64String(byte[] buffer)
        {
            if (buffer != null)
                return Convert.ToBase64String(buffer);

            return null;
        }
    }
}